package org.zhs.es.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.zhs.es.test.mappingVo.User;

import java.io.IOException;

/**
 * @Author: zhs
 * @Date: 2021/6/24 11:06
 * @Description:
 *
 * 插入文档
 *
 */
public class ESTest_Document_Insert {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient rsClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));


        //插入数据
        IndexRequest request = new IndexRequest();
        request.index("user").id("1001");
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setSex("男");
        //向es插入数据，必须将数据转换成JSON格式
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);

        IndexResponse response = rsClient.index(request, RequestOptions.DEFAULT);

        System.out.println(response.getResult());


        //关闭客户端
        rsClient.close();
    }
}
